/*
 * DBServer.java
 *
 * Created on 21 de Outubro de 2007, 16:20
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package Remote;


import DB.DataAccess;
import Util.Observer;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Ronaldinho
 */
public class DBServer extends Connectable {
    
    private Observer observer;
    private DataAccess dataAccess;
    
    /** Creates a new instance of DBServer */
    public DBServer(int receivePort, int sendPort, DataAccess dataAccess, Observer observer) throws IOException {
        super(receivePort, sendPort);
        this.observer = observer;
        this.dataAccess = dataAccess;
    }
    
    protected void conectar() {
        try {
            this.receberMensagem();
            
            Vector<Object> info = this.message.info;
            this.connectionEnded = this.message.end;
            
            Message m;
            if(!this.connectionEnded)
            {
                m = new Message(this.dataAccess.access(info), false);
                this.enviarMensagem(this.ip, m);
                
            }
            else
            {
                m = new Message(null, true);
                this.enviarMensagem(this.ip, message);
            }
            
        } catch (IOException ex) {
            Logger.getLogger(DBServer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DBServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void run() {
        System.out.println("start DBserver");
        while(!this.connectionEnded){
            this.conectar();
        }
        Vector<Object> info = new Vector<Object>();
        info.add(new Integer(this.receivePort).toString());
        info.add(new Integer(this.sendPort).toString());
        
        this.observer.observe(info);
        System.out.println("end DBserver");
    }
}
